package com.submit.demo.service.impl;

import com.submit.demo.common.api.CommonPage;
import com.submit.demo.model.ColSub;
import com.submit.demo.model.ColTag;
import com.submit.demo.model.SubTask;
import com.submit.demo.model.Submitter;
import com.submit.demo.repository.ColSubRepository;
import com.submit.demo.repository.ColTagRepository;
import com.submit.demo.repository.SubmitterRepository;
import com.submit.demo.service.ColSubService;
import com.submit.demo.util.MongoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ColSubServiceImpl implements ColSubService {
    @Autowired
    private ColSubRepository colSubRepository;

    @Autowired
    private SubmitterRepository submitterRepository;

    @Autowired
    private MongoUtil mongoUtil;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ColTagRepository colTagRepository;

    @Override
    public List<Submitter> listAll(String cid) {
        List<ColSub> colSub = colSubRepository.findColSubsByCid(cid);
        List<String> sids = colSub.stream().map(ColSub::getSid).collect(Collectors.toList());
        return submitterRepository.findAllById(sids);
    }

    @Override
    public Integer insertTagWithSubs(String cid, String tag, List<String> ids) {
        List<ColSub> list = new ArrayList<>();
        ColTag colTag = colTagRepository.findColTagByCid(cid);
        if(!colTag.getTags().contains(tag)){
            colTag.getTags().add(tag);
            colTagRepository.save(colTag);
        }
        for(String sid : ids){
            ColSub colSub = colSubRepository.findColSubByCidAndSid(cid, sid);
            if(!colSub.getTags().contains(tag)) colSub.getTags().add(tag);
            list.add(colSub);
        }
        colSubRepository.saveAll(list);
        return 1;
    }

    @Override
    public CommonPage<Submitter> list(String cid, Integer currentPage, Integer pageSize) {
        Query query = new Query(Criteria.where("cid").is(cid));
        long count = mongoTemplate.count(query, ColSub.class);
        mongoUtil.start(currentPage, pageSize, query);
        List<ColSub> list = mongoTemplate.find(query, ColSub.class);
        if(list == null) return null;
        List<String> sids = list.stream().map(ColSub::getSid).collect(Collectors.toList());
        query = new Query(Criteria.where("id").in(sids));
        List<Submitter> submitters = mongoTemplate.find(query, Submitter.class);
        return mongoUtil.pageHelper(count, submitters);
    }
}
